const bcrypt = require("bcryptjs");
const { getUserInfo } = require("../service/user.service");
const {
  userFormateError,
  userAlreadyExited,
  userDoesNotExist,
  userLoginError,
  invalidPassword,
} = require("../constant/err.type");
const userValidator = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;
  //todo 合法性 检验提交的用户名和密码是否为空
  if (!user_name || !password) {
    console.error("注册的用户名或密码为空", ctx.request.body);
    /*  ctx.status = 400;
    ctx.body = {
      code: "10001",
      message: "用户名或密码为空",
      result: "",
    }; */
    ctx.app.emit("error", userFormateError, ctx);
    return;
  }

  await next();
};

const verifyUser = async (ctx, next) => {
  const { user_name } = ctx.request.body;
  //todo 合理性 检验注册新用户的用户名是否已存在
  /* if (await getUserInfo({ user_name })) {
    ctx.status = 409; //*409代表数据冲突
    ctx.body = {
      code: "10002",
      message: "用户名已经存在",
      result: "",
    };
    return;
  } */
  if (await getUserInfo({ user_name })) {
    console.error("用户名已经存在", { user_name });
    ctx.app.emit("error", userAlreadyExited, ctx);
    return;
  }
  await next();
};

const cryptPassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  const salt = bcrypt.genSaltSync(10); //* 十次加盐加密
  //* hash保存的是密文
  const hash = bcrypt.hashSync(password, salt);

  ctx.request.body.password = hash;
  await next();
};

const verifyLogin = async (ctx, next) => {
  //* 1. 判断用户是否存在(不存在: 报错)
  const { user_name, password } = ctx.request.body;

  try {
    const res = await getUserInfo({ user_name });

    if (!res) {
      console.error("用户名不存在", { user_name });
      ctx.app.emit("error", userDoesNotExist, ctx);
      return;
    }

    //* 2. 密码是否匹配(不匹配: 报错)
    if (!bcrypt.compareSync(password, res.password)) {
      console.error("用户密码输入错误");
      ctx.app.emit("error", invalidPassword, ctx);
      return;
    }
  } catch (err) {
    return console.error("error", userLoginError, ctx);
  }

  await next();
};

module.exports = {
  userValidator,
  verifyUser,
  cryptPassword,
  verifyLogin,
};
